﻿using RockBus.Configuration.Interfaces;
using RockBus.DataContracts;
using RockBus.Initialization.Interfaces;
using RockBus.Routing.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RockBus.Initialization
{
    public class ConfigurationInitialization : IInitialization
    {
        public ConfigurationInitialization(IConfigurationManager configurationManager, IReadOnlyConfiguration configuration)
        {
            this.ConfigurationManager = configurationManager;
            this.Configuration = configuration;
        }

        private IConfigurationManager ConfigurationManager { get; set; }

        private IReadOnlyConfiguration Configuration { get; set; }

        public void Initialize()
        {
            RockBus.Configuration.ConfigurationRepository configRepository = new Configuration.ConfigurationRepository();
            var internalConfig = configRepository.GetInternalConfiguration();
            var subscriberConfig = configRepository.GetSubscriberConfiguration();
            var publisherConfig = configRepository.GetPublisherConfiguration();

            if (internalConfig != null)
            {
                this.ConfigurationManager.SetInternalConfiguration(new SetInternalConfigurationRequest(internalConfig));
            }

            if ((subscriberConfig != null) &&
                (subscriberConfig.EvaluationElementDictionary != null) &&
                (subscriberConfig.EvaluationElementDictionary.Count > 0))
            {
                this.ConfigurationManager.AddOrUpdateSubscribers(new AddOrUpdateSubscribersRequest(subscriberConfig));
            }

            if ((publisherConfig != null) &&
                (publisherConfig.EvaluationElementDictionary != null) &&
                (publisherConfig.EvaluationElementDictionary.Count > 0))
            {
                this.ConfigurationManager.AddOrUpdatePublishers(new AddOrUpdatePublishersRequest(publisherConfig));
            }

            this.Configuration.Refresh();
        }
    }
}
